package org.micro.rbac.core.config;


import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.micro.rbac.core.exception.AuthException;
import org.micro.rbac.core.exception.BizException;
import org.micro.rbac.core.exception.GrantException;
import org.micro.rbac.core.result.Code;
import org.micro.rbac.core.result.R;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 默认的异常处理
 *
 * @author hongsir
 * @since 2023-05-24
 **/
@Slf4j
@RestController
@RestControllerAdvice
public class MyExceptionAdvice implements ErrorController {
    /**
     * 重写默认的异常处理,例如:404等
     *
     * @param request 请求对象
     * @return json
     */
    @RequestMapping("/error")
    public R<String> error(HttpServletRequest request) {
        String obj = (String) request.getAttribute("jakarta.servlet.forward.servlet_path");
        return R.fail(obj, Code.NOT_FOUND_ERROR.message());
    }

    /**
     * 运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R<Void> runtimeExceptionHandler(RuntimeException ex) {
        log.error("运行时异常:{}", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * 空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public R<Void> nullPointerExceptionHandler(NullPointerException ex) {
        log.error("空指针异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    @ExceptionHandler({MissingServletRequestParameterException.class})
    public R<Void> badRequestException(MissingServletRequestParameterException e) {
        log.error("缺少必传参数:{} ", e.getMessage(), e);
        return R.fail("缺少必传参数:" + e.getMessage());
    }

    @ExceptionHandler({ParseException.class})
    public R<Void> badRequestException(ParseException e) {
        log.error("数据类型错误:{} ", e.getMessage(), e);
        return R.fail("数据类型错误");
    }

    @ExceptionHandler({IllegalArgumentException.class})
    public R<Void> badRequestException(IllegalArgumentException e) {
        log.error("参数解析失败:{} ", e.getMessage(), e);
        return R.fail("参数结构错误");
    }

    @ExceptionHandler({NoHandlerFoundException.class})
    public R<Void> badRequestException(NoHandlerFoundException e) {
        return R.fail("访问的服务不存在或已停用");
    }

    /**
     * 类型转换异常
     */
    @ExceptionHandler(ClassCastException.class)
    public R<Void> classCastExceptionHandler(ClassCastException ex) {
        log.error("类型转换异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * 文件未找到异常
     */
    @ExceptionHandler(FileNotFoundException.class)
    public R<Void> fileNotFoundException(FileNotFoundException ex) {
        log.error("文件未找到异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * 数字格式异常
     */
    @ExceptionHandler(NumberFormatException.class)
    public R<Void> numberFormatException(NumberFormatException ex) {
        log.error("数字格式异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * 安全异常
     */
    @ExceptionHandler(SecurityException.class)
    public R<Void> securityException(SecurityException ex) {
        log.error("安全异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }


    /**
     * 类型不存在异常
     */
    @ExceptionHandler(TypeNotPresentException.class)
    public R<Void> typeNotPresentException(TypeNotPresentException ex) {
        log.error("类型不存在异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * IO异常
     */
    @ExceptionHandler(IOException.class)
    public R<Void> ioExceptionHandler(IOException ex) {
        log.error("IO异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * 未知方法异常
     */
    @ExceptionHandler(NoSuchMethodException.class)
    public R<Void> noSuchMethodExceptionHandler(NoSuchMethodException ex) {
        log.error("未知方法异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * 数组越界异常
     */
    @ExceptionHandler(IndexOutOfBoundsException.class)
    public R<Void> indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
        log.error("数组越界异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * sql异常
     */
    @ExceptionHandler(SQLException.class)
    public R<Void> SQLException(SQLException ex) {
        log.error("sql异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * 无法注入bean异常
     */
    @ExceptionHandler(NoSuchBeanDefinitionException.class)
    public R<Void> noSuchBeanDefinitionException(NoSuchBeanDefinitionException ex) {
        log.error("无法注入bean异常 :{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * Http消息不可读异常
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public R<Void> requestNotReadable(HttpMessageNotReadableException ex) {
        log.error("400错误..requestNotReadable:{} ", ex.getMessage(), ex);
        return R.fail("请求参数格式错误,请核查");
    }

    /**
     * 400错误
     */
    @ExceptionHandler({TypeMismatchException.class})
    public R<Void> requestTypeMismatch(TypeMismatchException ex) {
        log.error("400错误..TypeMismatchException:{} ", ex.getMessage(), ex);
        return R.fail("请求参数类型错误,请核查");
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R<Void> badRequestException(MethodArgumentNotValidException e) {
        StringBuilder message = new StringBuilder();
        List<ObjectError> allError = e.getBindingResult().getAllErrors();
        for (ObjectError error : allError) {
            message.append(error.getDefaultMessage()).append(".");
        }
        return R.fail(message.toString());
    }

    /**
     * 500错误
     */
    @ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    public R<Void> server500(RuntimeException ex) {
        log.error("500错误:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * 栈溢出
     */
    @ExceptionHandler({StackOverflowError.class})
    public R<Void> requestStackOverflow(StackOverflowError ex) {
        log.error("栈溢出:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    /**
     * 除数不能为0
     */
    @ExceptionHandler({ArithmeticException.class})
    public R<Void> arithmeticException(ArithmeticException ex) {
        log.error("除数不能为0:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public R<Void> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        if (HttpMethod.GET.matches(e.getMethod())) {
            return R.fail("该接口不支持GET请求");
        } else if (HttpMethod.POST.matches(e.getMethod())) {
            return R.fail("该接口不支持POST请求");
        }
        return R.fail("该接口仅支持GET/POST请求");
    }

    @ExceptionHandler(BizException.class)
    public R<Void> biz(BizException e) {
        return R.fail(e.getMessage());
    }

    @ExceptionHandler(AuthException.class)
    public R<Void> auth(BizException e) {
        return R.fail(Code.NOT_LOGIN.code());
    }

    @ExceptionHandler(GrantException.class)
    public R<Void> grant(BizException e) {
        return R.fail(Code.NOT_GRANT.code());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public R<Void> constraintViolationException(HttpServletRequest request, HttpServletResponse response, ConstraintViolationException e) {
        StringBuilder message = new StringBuilder();
        Set<ConstraintViolation<?>> allError = e.getConstraintViolations();
        for (ConstraintViolation<?> error : allError) {
            message.append(error.getMessage()).append(";");
        }
        log.error("请求接口单参数校验异常<ConstraintViolationException>:【{}】-【{}】", request.getRequestURI(), message);
        return R.fail(message.toString());
    }

    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    public R<Void> handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
        //application/x-www-form-urlencoded;charset=UTF-8
        //application/json;charset=UTF-8
        return R.fail("不支持当前媒体类型,请检查Content-Type");
    }

    /**
     * 其他错误
     */
    @ExceptionHandler({Exception.class})
    public R<Void> exception(Exception ex) {
        log.error("未知异常:{} ", ex.getMessage(), ex);
        return R.fail(Code.SYS_ERROR.message());
    }

    @ExceptionHandler({BindException.class})
    public R<Void> bindException(BindException e) {
        StringBuilder message = new StringBuilder();
        for (ObjectError error : e.getAllErrors()) {
            message.append(error.getDefaultMessage()).append(";");
        }
        String msg = message.toString();
        if (msg.contains("NumberFormatException")) {
            String regex = "property '(.*?)'|For input string: \"(.*?)\";";
            Pattern pattern = Pattern.compile(regex);
            Matcher m = pattern.matcher(message);
            StringBuilder temp = new StringBuilder();
            while (m.find()) {
                String p = m.group(1);
                String v = m.group(2);
                if (StrUtil.isNotBlank(p)) {
                    temp.append(p);
                }
                if (StrUtil.isNotBlank(v)) {
                    temp.append("=").append(v).append(";");
                }
            }
            return R.fail("参数类型错误:" + temp);
        }
        return R.fail(msg);
    }
}
